package com.fadadianqi.logistics.admin.plugins.gree;

import com.fadadianqi.logistics.admin.printer.PrintService;
import com.fadadianqi.commons.ConfigHelper;
import com.fadadianqi.commons.Constants;
import com.yeqiangwei.commons.io.FileHelper;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.awt.print.Paper;
import java.io.StringWriter;
import java.util.Properties;

public class PrintInstallCardService {

    private static final Logger log = Logger.getLogger(PrintInstallCardService.class);

    private InstallCard card;
    private String baseDir;
    private VelocityEngine ve = new VelocityEngine();

    public PrintInstallCardService(InstallCard card) {
        this.card = card;
        this.baseDir = Constants.getBaseDir();
    }

    public void doPrint() throws Exception {
        int offsetX = ConfigHelper.getInt("vm.printer.offsetX", 10);
        int offsetY = ConfigHelper.getInt("vm.printer.offsetY", 10);
        int width = ConfigHelper.getInt("vm.printer.width", 585);
        int height = ConfigHelper.getInt("vm.printer.height", 800);
        Paper p = new Paper();
        p.setSize(width, height); // 纸张大小
        p.setImageableArea(offsetX, offsetY, width, height);
        PrintService printService = new PrintService(getContent(), p);
        printService.localPrint();
    }

    private String getContent() throws Exception {
        String path = baseDir + "gree" + FileHelper.separator;
        log.debug(Velocity.FILE_RESOURCE_LOADER_PATH + ": " + path);
        Properties properties = new Properties();
        properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path);
        properties.setProperty(Velocity.INPUT_ENCODING, Constants.UTF_8);
        properties.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF_8);
        properties.setProperty(Velocity.FILE_RESOURCE_LOADER_CACHE, "false");
        ve.init(properties);
        Template t = ve.getTemplate("installNormal.vm");
        VelocityContext context = new VelocityContext();
        context.put("card", card);
        StringWriter writer = new StringWriter();
        t.merge(context, writer);
        writer.flush();
        writer.close();
        return (writer.toString());
    }
}
